import {defineComponent} from "vue";
import {getToken} from "@/utils/auth";
import {ElMessage} from "element-plus";

export default defineComponent({
    props:{
        fileList:{
            type:Array,
            default:()=>[]
        }
    },
    setup(props){
        const handleAvatarSuccess = (response, uploadFile) => {
            if (props.fileList.value.length > 1) {
                props.fileList.value.shift()
            }
        }

        const beforeAvatarUpload = (rawFile) => {
            if (rawFile.size / 1024 / 1024 > 2) {
                ElMessage.error('Avatar picture size can not exceed 2MB!')
                return false
            }else if(!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)){
                ElMessage.error('不支持的文件格式')
                return false
            }
            return true
        }

        return ()=>{
            return <>
                <el-upload
                    v-model:file-list={props.fileList.value}
                    className="avatar-uploader"
                    list-type={"picture-card"}
                    action={'/api/other/upload'}
                    headers={{
                        'Authorization': 'Bearer ' + getToken()
                    }}
                    onSuccess={handleAvatarSuccess}
                    beforeUpload={beforeAvatarUpload}
                >
                    <el-icon><Plus/></el-icon>
                </el-upload>
            </>
        }
    }
})